<template>
  <div class="behavior-profile">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h2>行为画像分析</h2>
        <p>深入分析用户行为模式，了解用户活跃度和偏好</p>
      </div>
      <div class="header-actions">
        <el-select v-model="timeRange" size="small" style="width: 120px">
          <el-option label="最近7天" value="7d" />
          <el-option label="最近30天" value="30d" />
          <el-option label="最近90天" value="90d" />
        </el-select>
        <el-button :icon="Refresh" @click="refreshData" :loading="loading">刷新</el-button>
        <el-button type="primary" :icon="Download" @click="exportReport">导出报告</el-button>
      </div>
    </div>

    <!-- 行为指标概览 -->
    <div class="behavior-metrics" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" v-for="metric in behaviorMetrics" :key="metric.key">
          <el-card class="metric-card" :class="metric.key">
            <div class="metric-content">
              <div class="metric-icon">
                <el-icon :size="28" :color="metric.color">
                  <component :is="metric.icon" />
                </el-icon>
              </div>
              <div class="metric-info">
                <h3>{{ metric.title }}</h3>
                <p class="metric-value">{{ metric.value }}</p>
                <span class="metric-change" :class="metric.trend">
                  <el-icon :size="12">
                    <component :is="metric.trend === 'up' ? 'ArrowUp' : 'ArrowDown'" />
                  </el-icon>
                  {{ metric.change }}
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 行为分析图表 -->
    <div class="behavior-charts">
      <el-row :gutter="20">
        <!-- 行为类型分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>行为类型分布</h3>
                <el-button-group size="small">
                  <el-button :type="behaviorChartType === 'pie' ? 'primary' : ''" @click="behaviorChartType = 'pie'">
                    饼图
                  </el-button>
                  <el-button :type="behaviorChartType === 'bar' ? 'primary' : ''" @click="behaviorChartType = 'bar'">
                    柱状图
                  </el-button>
                </el-button-group>
              </div>
            </template>
            <div class="chart-container">
              <PieChartComponent
                v-if="behaviorChartType === 'pie'"
                :data="behaviorTypeData"
                height="300px"
                :radius="['40%', '70%']"
                @chart-click="handleBehaviorTypeClick"
              />
              <BaseChart
                v-else
                :option="behaviorTypeBarOption"
                height="300px"
                @chart-click="handleBehaviorTypeClick"
              />
            </div>
          </el-card>
        </el-col>

        <!-- 活跃时段分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>活跃时段分析</h3>
                <el-select v-model="activeTimeType" size="small" style="width: 100px">
                  <el-option label="小时" value="hour" />
                  <el-option label="星期" value="week" />
                </el-select>
              </div>
            </template>
            <div class="chart-container">
              <BaseChart
                :option="activeTimeOption"
                height="300px"
                @chart-click="handleActiveTimeClick"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 用户路径分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>用户路径分析</h3>
                <el-tag size="small" type="info">热门路径</el-tag>
              </div>
            </template>
            <div class="path-analysis">
              <div class="path-item" v-for="path in userPaths" :key="path.id">
                <div class="path-flow">
                  <div class="path-step" v-for="(step, index) in path.steps" :key="index">
                    <span class="step-name">{{ step }}</span>
                    <el-icon v-if="index < path.steps.length - 1" class="step-arrow">
                      <ArrowRight />
                    </el-icon>
                  </div>
                </div>
                <div class="path-stats">
                  <span class="path-count">{{ path.count }}人</span>
                  <span class="path-rate">{{ path.rate }}%</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 设备使用分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <h3>设备使用分析</h3>
                <span class="chart-total">总访问: {{ deviceData.reduce((sum, item) => sum + item.value, 0).toLocaleString() }}</span>
              </div>
            </template>
            <div class="chart-container">
              <PieChartComponent
                :data="deviceData"
                height="300px"
                :radius="['30%', '60%']"
                @chart-click="handleDeviceClick"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 行为趋势分析 -->
    <div class="behavior-trends">
      <el-card>
        <template #header>
          <div class="chart-header">
            <h3>行为趋势分析</h3>
            <div class="trend-controls">
              <el-checkbox-group v-model="selectedBehaviors" size="small">
                <el-checkbox label="浏览">浏览</el-checkbox>
                <el-checkbox label="购买">购买</el-checkbox>
                <el-checkbox label="加购物车">加购物车</el-checkbox>
                <el-checkbox label="收藏">收藏</el-checkbox>
                <el-checkbox label="搜索">搜索</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </template>
        <div class="chart-container" style="height: 400px;">
          <BaseChart
            :option="behaviorTrendOption"
            height="400px"
            @chart-click="handleTrendClick"
          />
        </div>
      </el-card>
    </div>

    <!-- 行为详细分析表格 -->
    <div class="behavior-table">
      <el-card>
        <template #header>
          <div class="table-header">
            <h3>行为详细分析</h3>
            <div class="table-controls">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索行为..."
                size="small"
                style="width: 200px"
                :prefix-icon="Search"
                clearable
              />
              <el-select v-model="behaviorFilter" size="small" style="width: 120px">
                <el-option label="全部行为" value="" />
                <el-option label="浏览" value="view" />
                <el-option label="购买" value="purchase" />
                <el-option label="加购物车" value="add_cart" />
                <el-option label="收藏" value="favorite" />
                <el-option label="搜索" value="search" />
              </el-select>
            </div>
          </div>
        </template>

        <el-table :data="tableData" v-loading="tableLoading" stripe style="width: 100%">
          <el-table-column prop="behavior" label="行为类型" min-width="120">
            <template #default="{ row }">
              <el-tag :type="getBehaviorTagType(row.behavior)" size="small">
                {{ getBehaviorText(row.behavior) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalCount" label="总次数" min-width="120">
            <template #default="{ row }">
              {{ row.totalCount.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="uniqueUsers" label="独立用户" min-width="120">
            <template #default="{ row }">
              {{ row.uniqueUsers.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column prop="avgFrequency" label="平均频次" min-width="120" />
          <el-table-column prop="peakHour" label="高峰时段" min-width="120" />
          <el-table-column prop="conversionRate" label="转化率" min-width="100">
            <template #default="{ row }">
              {{ row.conversionRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="trend" label="趋势" min-width="120">
            <template #default="{ row }">
              <el-tag :type="row.trend === 'up' ? 'success' : row.trend === 'down' ? 'danger' : 'info'" size="small">
                <el-icon>
                  <component :is="row.trend === 'up' ? 'ArrowUp' : row.trend === 'down' ? 'ArrowDown' : 'Minus'" />
                </el-icon>
                {{ row.trendText }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="viewBehaviorDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="totalRecords"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh, Download, Search, ArrowUp, ArrowDown, ArrowRight, Minus,
  View, ShoppingCart, Star, Search as SearchIcon, Monitor
} from '@element-plus/icons-vue'
import { BaseChart, PieChart as PieChartComponent } from '@/components/charts'
import { getBehaviorProfileAnalysis } from '@/api/analysis'

// 响应式数据
const loading = ref(false)
const timeRange = ref('30d')
const behaviorChartType = ref('pie')
const activeTimeType = ref('hour')
const selectedBehaviors = ref(['浏览', '购买', '加购物车'])
const searchKeyword = ref('')
const behaviorFilter = ref('')
const tableLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalRecords = ref(0)

// API数据存储
const apiData = ref({
  activity_distribution: [],
  login_frequency: [],
  site_engagement: [],
  newsletter_subscription: [],
  summary: {
    avg_time_on_site: 0,
    avg_pages_viewed: 0,
    avg_last_login: 0
  }
})

// 行为指标数据（基于API数据计算）
const behaviorMetrics = computed(() => {
  const highActiveUsers = apiData.value.activity_distribution.find(item => item.label === '高活跃')?.value || 0
  const totalUsers = apiData.value.activity_distribution.reduce((sum, item) => sum + item.value, 0)
  const avgTimeOnSite = apiData.value.summary.avg_time_on_site || 0
  const avgPagesViewed = apiData.value.summary.avg_pages_viewed || 0

  return [
    {
      key: 'avg_time_on_site',
      title: '平均停留时间',
      value: `${avgTimeOnSite}分钟`,
      change: '+12.3%',
      trend: 'up',
      icon: 'Timer',
      color: '#409EFF'
    },
    {
      key: 'active_users',
      title: '高活跃用户',
      value: highActiveUsers.toLocaleString(),
      change: '+8.7%',
      trend: 'up',
      icon: 'Monitor',
      color: '#67C23A'
    },
    {
      key: 'avg_pages',
      title: '平均浏览页面',
      value: `${avgPagesViewed}页`,
      change: '+5.2%',
      trend: 'up',
      icon: 'View',
      color: '#E6A23C'
    },
    {
      key: 'total_users',
      title: '总用户数',
      value: totalUsers.toLocaleString(),
      change: '+3.1%',
      trend: 'up',
      icon: 'User',
      color: '#F56C6C'
    }
  ]
})

// 行为类型分布数据（基于API数据和模拟数据混合）
const behaviorTypeData = computed(() => {
  // 基于活跃度分布生成行为类型数据
  const totalUsers = apiData.value.activity_distribution.reduce((sum, item) => sum + item.value, 0)

  if (totalUsers === 0) {
    // 使用模拟数据
    return [
      { name: '浏览', value: 1580000 },
      { name: '搜索', value: 680000 },
      { name: '加购物车', value: 320000 },
      { name: '收藏', value: 180000 },
      { name: '购买', value: 95000 }
    ]
  }

  // 基于用户数量估算行为数据
  return [
    { name: '浏览', value: Math.round(totalUsers * 9.8) }, // 平均每用户9.8次浏览
    { name: '搜索', value: Math.round(totalUsers * 4.2) }, // 平均每用户4.2次搜索
    { name: '加购物车', value: Math.round(totalUsers * 2.0) }, // 平均每用户2.0次加购物车
    { name: '收藏', value: Math.round(totalUsers * 1.1) }, // 平均每用户1.1次收藏
    { name: '购买', value: Math.round(totalUsers * 0.6) }  // 平均每用户0.6次购买
  ]
})

// 活跃时段数据（基于API数据生成）
const hourlyActiveData = computed(() => {
  const totalUsers = apiData.value.activity_distribution.reduce((sum, item) => sum + item.value, 0)

  if (totalUsers === 0) {
    // 使用模拟数据
    return [
      { hour: '00:00', count: 12000 }, { hour: '01:00', count: 8500 }, { hour: '02:00', count: 6200 },
      { hour: '03:00', count: 4800 }, { hour: '04:00', count: 5200 }, { hour: '05:00', count: 7800 },
      { hour: '06:00', count: 15600 }, { hour: '07:00', count: 28900 }, { hour: '08:00', count: 45200 },
      { hour: '09:00', count: 58600 }, { hour: '10:00', count: 68900 }, { hour: '11:00', count: 72300 },
      { hour: '12:00', count: 65800 }, { hour: '13:00', count: 58200 }, { hour: '14:00', count: 62500 },
      { hour: '15:00', count: 68900 }, { hour: '16:00', count: 72100 }, { hour: '17:00', count: 75600 },
      { hour: '18:00', count: 78900 }, { hour: '19:00', count: 82300 }, { hour: '20:00', count: 85600 },
      { hour: '21:00', count: 78200 }, { hour: '22:00', count: 65800 }, { hour: '23:00', count: 45200 }
    ]
  }

  // 基于用户活跃度生成小时分布数据
  const baseActivity = totalUsers * 0.5 // 基础活跃度
  const hourlyPattern = [0.14, 0.1, 0.07, 0.06, 0.06, 0.09, 0.18, 0.34, 0.53, 0.69, 0.81, 0.85,
                         0.77, 0.68, 0.73, 0.81, 0.85, 0.89, 0.93, 0.97, 1.0, 0.92, 0.77, 0.53]

  return hourlyPattern.map((factor, index) => ({
    hour: `${index.toString().padStart(2, '0')}:00`,
    count: Math.round(baseActivity * factor)
  }))
})

const weeklyActiveData = computed(() => {
  const totalUsers = apiData.value.activity_distribution.reduce((sum, item) => sum + item.value, 0)

  if (totalUsers === 0) {
    return [
      { day: '周一', count: 850000 }, { day: '周二', count: 920000 }, { day: '周三', count: 880000 },
      { day: '周四', count: 950000 }, { day: '周五', count: 1020000 }, { day: '周六', count: 1180000 },
      { day: '周日', count: 1050000 }
    ]
  }

  // 基于用户数生成周活跃数据
  const weeklyPattern = [0.72, 0.78, 0.75, 0.81, 0.87, 1.0, 0.89]
  const baseWeeklyActivity = totalUsers * 5.3 // 每用户每周平均活跃次数

  return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'].map((day, index) => ({
    day,
    count: Math.round(baseWeeklyActivity * weeklyPattern[index])
  }))
})

// 用户路径数据（基于API数据生成）
const userPaths = computed(() => {
  const totalUsers = apiData.value.activity_distribution.reduce((sum, item) => sum + item.value, 0)

  if (totalUsers === 0) {
    // 使用模拟数据
    return [
      { id: 1, steps: ['首页', '商品列表', '商品详情', '购买'], count: 15680, rate: 28.5 },
      { id: 2, steps: ['搜索', '商品详情', '加购物车', '购买'], count: 12450, rate: 22.6 },
      { id: 3, steps: ['首页', '分类页', '商品详情', '收藏'], count: 9800, rate: 17.8 },
      { id: 4, steps: ['商品详情', '对比', '购买'], count: 8650, rate: 15.7 },
      { id: 5, steps: ['搜索', '筛选', '商品详情'], count: 8520, rate: 15.4 }
    ]
  }

  // 基于用户数生成路径数据
  const pathPatterns = [
    { id: 1, steps: ['首页', '商品列表', '商品详情', '购买'], factor: 0.285 },
    { id: 2, steps: ['搜索', '商品详情', '加购物车', '购买'], factor: 0.226 },
    { id: 3, steps: ['首页', '分类页', '商品详情', '收藏'], factor: 0.178 },
    { id: 4, steps: ['商品详情', '对比', '购买'], factor: 0.157 },
    { id: 5, steps: ['搜索', '筛选', '商品详情'], factor: 0.154 }
  ]

  return pathPatterns.map(pattern => ({
    id: pattern.id,
    steps: pattern.steps,
    count: Math.round(totalUsers * pattern.factor),
    rate: (pattern.factor * 100).toFixed(1)
  }))
})

// 设备使用数据（基于API数据生成）
const deviceData = computed(() => {
  const totalUsers = apiData.value.activity_distribution.reduce((sum, item) => sum + item.value, 0)

  if (totalUsers === 0) {
    return [
      { name: '手机', value: 1680000 },
      { name: '电脑', value: 850000 },
      { name: '平板', value: 320000 }
    ]
  }

  // 基于用户数生成设备使用数据
  return [
    { name: '手机', value: Math.round(totalUsers * 0.68) }, // 68%用户使用手机
    { name: '电脑', value: Math.round(totalUsers * 0.25) }, // 25%用户使用电脑
    { name: '平板', value: Math.round(totalUsers * 0.07) }  // 7%用户使用平板
  ]
})

// 行为趋势数据
const behaviorTrendData = ref({
  dates: ['01-01', '01-02', '01-03', '01-04', '01-05', '01-06', '01-07', '01-08', '01-09', '01-10'],
  浏览: [85000, 88000, 92000, 89000, 95000, 98000, 102000, 96000, 99000, 105000],
  购买: [4200, 4500, 4800, 4600, 5100, 5300, 5600, 5200, 5400, 5800],
  加购物车: [12000, 12800, 13500, 13200, 14100, 14600, 15200, 14800, 15100, 15900],
  收藏: [6800, 7200, 7600, 7400, 7900, 8200, 8600, 8300, 8500, 8900],
  搜索: [28000, 29500, 31000, 30200, 32500, 33800, 35200, 34600, 35800, 37200]
})

// 表格数据
const mockTableData = ref([
  {
    behavior: 'view',
    totalCount: 1580000,
    uniqueUsers: 125600,
    avgFrequency: 12.6,
    peakHour: '20:00-21:00',
    conversionRate: 3.2,
    trend: 'up',
    trendText: '增长'
  },
  {
    behavior: 'search',
    totalCount: 680000,
    uniqueUsers: 89500,
    avgFrequency: 7.6,
    peakHour: '19:00-20:00',
    conversionRate: 8.5,
    trend: 'up',
    trendText: '增长'
  },
  {
    behavior: 'add_cart',
    totalCount: 320000,
    uniqueUsers: 65800,
    avgFrequency: 4.9,
    peakHour: '20:00-21:00',
    conversionRate: 15.8,
    trend: 'stable',
    trendText: '稳定'
  },
  {
    behavior: 'favorite',
    totalCount: 180000,
    uniqueUsers: 45200,
    avgFrequency: 4.0,
    peakHour: '21:00-22:00',
    conversionRate: 12.3,
    trend: 'up',
    trendText: '增长'
  },
  {
    behavior: 'purchase',
    totalCount: 95000,
    uniqueUsers: 38600,
    avgFrequency: 2.5,
    peakHour: '20:00-21:00',
    conversionRate: 100,
    trend: 'up',
    trendText: '增长'
  }
])

// 计算属性
const behaviorTypeBarOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 次'
    },
    xAxis: {
      type: 'category',
      data: behaviorTypeData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'bar',
      data: behaviorTypeData.value.map(item => item.value),
      itemStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#79bbff' }
          ]
        }
      }
    }]
  }
})

const activeTimeOption = computed(() => {
  const data = activeTimeType.value === 'hour' ? hourlyActiveData.value : weeklyActiveData.value
  const xAxisData = data.map(item => activeTimeType.value === 'hour' ? item.hour : item.day)

  return {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c} 次活动'
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        rotate: activeTimeType.value === 'hour' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      type: 'line',
      data: data.map(item => item.count),
      smooth: true,
      areaStyle: {
        opacity: 0.3,
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: 'rgba(103, 194, 58, 0)' }
          ]
        }
      },
      itemStyle: {
        color: '#67C23A'
      }
    }]
  }
})

const behaviorTrendOption = computed(() => {
  const series = selectedBehaviors.value.map((behavior, index) => {
    const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
    return {
      name: behavior,
      type: 'line',
      data: behaviorTrendData.value[behavior] || [],
      smooth: true,
      itemStyle: {
        color: colors[index % colors.length]
      }
    }
  })

  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: selectedBehaviors.value
    },
    xAxis: {
      type: 'category',
      data: behaviorTrendData.value.dates
    },
    yAxis: {
      type: 'value'
    },
    series
  }
})

const tableData = computed(() => {
  let data = [...mockTableData.value]

  if (behaviorFilter.value) {
    data = data.filter(item => item.behavior === behaviorFilter.value)
  }

  if (searchKeyword.value) {
    data = data.filter(item =>
      getBehaviorText(item.behavior).includes(searchKeyword.value)
    )
  }

  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value

  return data.slice(start, end)
})

// 加载行为画像分析数据
const loadBehaviorData = async () => {
  try {
    loading.value = true
    const response = await getBehaviorProfileAnalysis()

    if (response.success) {
      apiData.value = response.data
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '获取行为分析数据失败')
      // 使用模拟数据作为后备
      loadMockData()
    }
  } catch (error) {
    console.error('获取行为分析数据失败:', error)
    ElMessage.error('获取行为分析数据失败，使用模拟数据')
    // 使用模拟数据作为后备
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  apiData.value = {
    activity_distribution: [
      { label: '高活跃', value: 45600, percentage: 28.5 },
      { label: '中活跃', value: 78900, percentage: 49.3 },
      { label: '低活跃', value: 35500, percentage: 22.2 }
    ],
    login_frequency: [
      { label: '每日登录', value: 32400, percentage: 20.3 },
      { label: '每周登录', value: 56700, percentage: 35.4 },
      { label: '每月登录', value: 45200, percentage: 28.3 },
      { label: '偶尔登录', value: 25700, percentage: 16.0 }
    ],
    site_engagement: [
      { label: '高参与', value: 28900, percentage: 18.1 },
      { label: '中参与', value: 67800, percentage: 42.4 },
      { label: '低参与', value: 63300, percentage: 39.5 }
    ],
    newsletter_subscription: [
      { label: '已订阅', value: 89600, percentage: 56.0 },
      { label: '未订阅', value: 70400, percentage: 44.0 }
    ],
    summary: {
      avg_time_on_site: 12.5,
      avg_pages_viewed: 8.3,
      avg_last_login: 5.2
    }
  }
}

// 方法
const refreshData = async () => {
  await loadBehaviorData()
}

const exportReport = () => {
  ElMessage.success('报告导出功能开发中...')
}

const handleBehaviorTypeClick = (params) => {
  ElMessage.info(`点击了行为类型: ${params.name}，次数: ${params.value}`)
}

const handleActiveTimeClick = (params) => {
  ElMessage.info(`点击了时段: ${params.name}，活动次数: ${params.value}`)
}

const handleDeviceClick = (params) => {
  ElMessage.info(`点击了设备: ${params.name}，使用次数: ${params.value}`)
}

const handleTrendClick = (params) => {
  ElMessage.info(`点击了趋势数据: ${params.seriesName} - ${params.name}`)
}

const viewBehaviorDetail = (row) => {
  ElMessage.info(`查看 ${getBehaviorText(row.behavior)} 的详细信息`)
}

const getBehaviorTagType = (behavior) => {
  const typeMap = {
    view: '',
    search: 'info',
    add_cart: 'warning',
    favorite: 'danger',
    purchase: 'success'
  }
  return typeMap[behavior] || ''
}

const getBehaviorText = (behavior) => {
  const textMap = {
    view: '浏览',
    search: '搜索',
    add_cart: '加购物车',
    favorite: '收藏',
    purchase: '购买'
  }
  return textMap[behavior] || behavior
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 生命周期
onMounted(() => {
  totalRecords.value = mockTableData.value.length
  loadBehaviorData()
})
</script>

<style scoped>
.behavior-profile {
  padding: 0;
  background-color: transparent;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 行为指标 */
.behavior-metrics {
  margin-bottom: 24px;
}

.metric-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.metric-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.metric-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.metric-card:hover::before {
  opacity: 1;
}

.metric-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
}

.metric-icon {
  padding: 12px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.1);
}

.metric-info h3 {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.metric-value {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.metric-change {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.metric-change.up {
  color: #67C23A;
}

.metric-change.down {
  color: #F56C6C;
}

/* 图表区域 */
.behavior-charts {
  margin-bottom: 24px;
}

.chart-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.chart-total {
  color: #666;
  font-size: 14px;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.chart-container {
  height: 300px;
  padding: 20px 0;
}

/* 用户路径分析 */
.path-analysis {
  padding: 20px 0;
}

.path-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.path-item:hover {
  background: #e9ecef;
  transform: translateX(4px);
}

.path-flow {
  flex: 1;
}

.path-step {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.step-name {
  padding: 4px 8px;
  background: white;
  border-radius: 6px;
  font-size: 12px;
  color: #333;
  border: 1px solid #e0e0e0;
}

.step-arrow {
  color: #999;
  font-size: 12px;
}

.path-stats {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.path-count {
  font-weight: 600;
  color: #333;
}

.path-rate {
  font-size: 12px;
  color: #666;
}

/* 趋势分析 */
.behavior-trends {
  margin-bottom: 24px;
}

.behavior-trends .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.trend-controls {
  display: flex;
  align-items: center;
}

/* 表格 */
.behavior-table {
  width: 100%;
}

.behavior-table .el-card {
  border-radius: 16px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  width: 100%;
}

.behavior-table .el-table {
  width: 100% !important;
}

.behavior-table .el-card :deep(.el-card__body) {
  padding: 20px;
  width: 100%;
  overflow-x: auto;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.table-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .behavior-metrics .el-col {
    margin-bottom: 16px;
  }

  .behavior-charts .el-col {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .metric-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .chart-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }

  .trend-controls {
    justify-content: center;
  }

  .table-header {
    flex-direction: column;
    gap: 12px;
  }

  .table-controls {
    justify-content: center;
    flex-wrap: wrap;
  }

  .path-item {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }

  .path-stats {
    align-items: center;
  }

  .path-step {
    justify-content: center;
  }

  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .behavior-profile {
    padding: 0 16px;
  }

  .page-header {
    padding: 16px;
  }

  .metric-content {
    padding: 16px;
  }

  .metric-value {
    font-size: 20px;
  }

  .chart-container {
    height: 200px;
    padding: 10px 0;
  }

  .header-actions {
    flex-direction: column;
    width: 100%;
  }

  .header-actions .el-select,
  .header-actions .el-button {
    width: 100%;
  }

  .trend-controls .el-checkbox-group {
    flex-direction: column;
    gap: 8px;
  }

  .step-name {
    font-size: 10px;
    padding: 2px 6px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 360px) {
  .metric-content {
    padding: 12px;
  }

  .chart-container {
    height: 180px;
  }

  .table-controls {
    flex-direction: column;
    width: 100%;
  }

  .table-controls .el-input,
  .table-controls .el-select {
    width: 100% !important;
    margin-bottom: 8px;
  }

  .path-analysis {
    padding: 10px 0;
  }

  .path-item {
    padding: 12px;
  }
}
</style>
